﻿using System;
using System.Linq;
using PicoContainer;
using XEvolve.Core.Runtime.Attributes;

namespace XEvolve.Core.Runtime.Internal
{
    internal class AdapterManager : IStartable
    {
        private readonly IAdapterFactory[] adapterFactories;

        public AdapterManager([Extensions("xevolve.adapterFactories")]IAdapterFactory[] adapterFactories)
        {
            this.adapterFactories = adapterFactories;
        }

        internal object CreateAdapter(object adaptee, Type adapterType)
        {
            var adapterFactory = adapterFactories.SingleOrDefault(factory => factory.CanCreateAdapter(adaptee, adapterType));
            return adapterFactory != null ? adapterFactory.CreateAdapter(adaptee, adapterType) : null;
        }

        public void Start()
        {
            Adapters.Manager = this;
        }

        public void Stop()
        {
            Adapters.Manager = null;
        }
    }
}
